package org.example.cardgame.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.example.cardgame.entity.FlowManager;
import org.example.cardgame.entity.Message;
import org.example.cardgame.entity.Player;
import org.example.cardgame.service.PageHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author juanita.ren
 * @Date 2024/11/11 22:04
 * @Version 1.0
 */
@Component
@ServerEndpoint("/websocket/player")
public class PlayerWebSocket {
    private static Logger logger = LoggerFactory.getLogger(PlayerWebSocket.class);
    private static Map<Session, Map<String, Object>> sessionMap = new ConcurrentHashMap();
    private FlowManager flowManager = FlowManager.getInstance();

    public PlayerWebSocket() {
    }

    @OnOpen
    public void onOpen(Session session) {
        sessionMap.put(session, new HashMap<>());
        System.out.println("Connected ... " + session.getId());
    }

    @OnClose
    public void onClose(Session session) {
        sessionMap.remove(session);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        this.dealMessage(message, session);
    }

    @OnError
    public void onError(Session session, Throwable error) {
    }

    public static void sendMessageToPlayer(String msg, Player player) {
        Session session = player.getSession();
        if (session != null && session.isOpen()) {
            synchronized(session) {
                try {
                    session.getBasicRemote().sendText(msg);
                } catch (IOException var6) {
                    IOException e = var6;
                    logger.error("PageWebSocket::sendMessageToPlayer error:", e);
                }
            }
        }

    }

    public void dealMessage(String message, Session session) {
        try {
            logger.info("PlayerWebSocket::dealMessage message:" + message);
            JSONObject msgJson = JSON.parseObject(message);
            String type = msgJson.getString("type");
            JSONObject data = msgJson.getJSONObject("data");
            switch (type) {
                case "C_PlayerInfo":
                    sessionMap.put(session, data);
                    PageHandle.sendMessage(new Message("B_PlayerEnter", data));
                    break;
                case "C_PlayerOperate":
                    this.flowManager.receiveOperation(FlowManager.WaitOperation.PLAYER_OPERATE, data);
            }
        } catch (Exception var8) {
            Exception e = var8;
            logger.error("PageWebSocket::dealMessage error:", e);
        }

    }

    public static Map<Session, Map<String, Object>> getSessionMap() {
        return sessionMap;
    }
}

